package org.yczbj.ycvideoplayer.slice.music;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.ability.fraction.FractionScheduler;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.StackLayout;
import ohos.agp.components.Text;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import com.yc.music.inter.OnPlayerEventListener;
import com.yc.music.model.AudioBean;
import com.yc.music.tool.BaseAppHelper;

import org.yczbj.ycvideoplayer.ResourceTable;

import java.util.Optional;

/**
 * MusicPlayerSlice
 *
 * @since 2021-05-10
 */
public class MusicPlayerSlice extends AbilitySlice implements Component.ClickedListener {
    private static final int DELAY_TIME = 1000;
    private Text mTv1;
    private Text mTv2;
    private Text mTv3;
    private Text mTvStart;
    private Text mTvStop;
    private Text mTvNext;
    private Text mTvPre;
    private StackLayout mFlPlayBar;
    private Text mTvPlayBarTitle;
    private Image mIvPlayBarPlay;
    private ProgressBar mPbPlayBar;
    private boolean isPlayFragmentShow = false;
    private PlayMusicFragment mPlayFragment;
    private DirectionalLayout mLayout;

    @Override
    public void onBackPressed() {
        if (mPlayFragment != null && isPlayFragmentShow) {
            mLayout.setVisibility(Component.VISIBLE);
            hidePlayingFragment();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_music_player_slice);
        initFindViewById();
        initListener();
        runMainThread(new Runnable() {
            @Override
            public void run() {
                initPlayServiceListener();
            }
        });
    }

    /**
     * 切换任务到主线程执行
     *
     * @param runnable 执行的runnable
     */
    public void runMainThread(Runnable runnable) {
        EventRunner eventRunner = EventRunner.getMainEventRunner();
        EventHandler eventHandler = new EventHandler(eventRunner);
        eventHandler.postTask(runnable, DELAY_TIME);
    }

    private void initFindViewById() {
        mTv1 = (Text) findComponentById(ResourceTable.Id_tv_1);
        mTv2 = (Text) findComponentById(ResourceTable.Id_tv_2);
        mTv3 = (Text) findComponentById(ResourceTable.Id_tv_3);
        mTvStart = (Text) findComponentById(ResourceTable.Id_tv_start);
        mTvStop = (Text) findComponentById(ResourceTable.Id_tv_stop);
        mTvNext = (Text) findComponentById(ResourceTable.Id_tv_next);
        mTvPre = (Text) findComponentById(ResourceTable.Id_tv_pre);
        mFlPlayBar = (StackLayout) findComponentById(ResourceTable.Id_fl_play_bar);
        mTvPlayBarTitle = (Text) findComponentById(ResourceTable.Id_tv_play_bar_title);
        mIvPlayBarPlay = (Image) findComponentById(ResourceTable.Id_iv_play_bar_play);
        mPbPlayBar = (ProgressBar) findComponentById(ResourceTable.Id_pb_play_bar);
        mLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_layout);
    }

    private void initListener() {
        mTv1.setClickedListener(this);
        mTv2.setClickedListener(this);
        mTv3.setClickedListener(this);
        mTvStart.setClickedListener(this);
        mTvStop.setClickedListener(this);
        mTvNext.setClickedListener(this);
        mTvPre.setClickedListener(this);
        mIvPlayBarPlay.setClickedListener(this);
        mFlPlayBar.setClickedListener(this);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_tv_1:
                BaseAppHelper.get().getMusicService().play(0);
                break;
            case ResourceTable.Id_tv_start:
                mIvPlayBarPlay.setPixelMap(ResourceTable.Media_ic_play_bar_btn_pause);
                BaseAppHelper.get().getMusicService().start();
                break;
            case ResourceTable.Id_tv_stop:
                mIvPlayBarPlay.setPixelMap(ResourceTable.Media_ic_play_bar_btn_play);
                BaseAppHelper.get().getMusicService().stop();
                break;
            case ResourceTable.Id_tv_next:
                BaseAppHelper.get().getMusicService().next();
                break;
            case ResourceTable.Id_tv_pre:
                BaseAppHelper.get().getMusicService().prev();
                break;
            case ResourceTable.Id_fl_play_bar:
                mLayout.setVisibility(Component.HIDE);
                showPlayingFragment();
                break;
            case ResourceTable.Id_iv_play_bar_play:
                if (BaseAppHelper.get().getMusicService().isDefault()) {
                    mIvPlayBarPlay.setPixelMap(ResourceTable.Media_ic_play_bar_btn_pause);
                    if (BaseAppHelper.get().getMusicList().size() > 0) {
                        int mPlayPosition;
                        if (BaseAppHelper.get().getMusicService().getPlayingMusic() != null
                            && BaseAppHelper.get().getMusicService().getPlayingMusic().getType()
                            == AudioBean.Type.LOCAL) {
                            mPlayPosition = BaseAppHelper.get().getMusicService().getPlayingPosition();
                        } else {
                            mPlayPosition = 0;
                        }
                        BaseAppHelper.get().getMusicService().play(BaseAppHelper.get()
                            .getMusicList().get(mPlayPosition));
                    }
                } else {
                    BaseAppHelper.get().getMusicService().playPause();
                    mIvPlayBarPlay.setPixelMap(ResourceTable.Media_ic_play_bar_btn_play);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 初始化服务播放音频播放进度监听器
     * 这个是要是通过监听即时更新主页面的底部控制器视图
     * 同时还要同步播放详情页面mPlayFragment的视图
     */
    public void initPlayServiceListener() {
        if (BaseAppHelper.get() == null) {
            return;
        }
        BaseAppHelper.get().getMusicService().setOnPlayEventListener(new OnPlayerEventListener() {
            /**
             * 切换歌曲
             * 主要是切换歌曲的时候需要及时刷新界面信息
             *
             * @param music music
             */
            @Override
            public void onChange(AudioBean music) {
                onChangeImpl(music);
            }

            /**
             * 继续播放
             * 主要是切换歌曲的时候需要及时刷新界面信息，比如播放暂停按钮
             */
            @Override
            public void onPlayerStart() {
                mIvPlayBarPlay.setSelected(true);
            }

            /**
             * 暂停播放
             * 主要是切换歌曲的时候需要及时刷新界面信息，比如播放暂停按钮
             */
            @Override
            public void onPlayerPause() {
                mIvPlayBarPlay.setSelected(false);
            }

            /**
             * 更新进度
             * 主要是播放音乐或者拖动进度条时，需要更新进度
             *
             * @param progress progress
             */
            @Override
            public void onUpdateProgress(long progress) {
                mPbPlayBar.setProgressValue((int) progress);
            }

            @Override
            public void onBufferingUpdate(int percent) {
            }

            /**
             * 更新定时停止播放时间
             *
             * @param remain remain
             */
            @Override
            public void onTimer(long remain) {
            }
        });
    }

    /**
     * 当在播放音频详细页面切换歌曲的时候，需要刷新底部控制器，和音频详细页面的数据
     * 之前关于activity，Fragment，service之间用EventBus通信
     * 案例：https://github.com/yangchong211/LifeHelper
     * 本项目中直接通过定义接口来实现功能，尝试中……
     *
     * @param music LocalMusic
     */
    private void onChangeImpl(AudioBean music) {
        if (music == null) {
            return;
        }
        mTvPlayBarTitle.setText(music.getTitle());
        mIvPlayBarPlay.setSelected(BaseAppHelper.get().getMusicService().isPlaying() || BaseAppHelper.get()
            .getMusicService().isPreparing());

        // 更新进度条
        mPbPlayBar.setMaxValue((int) music.getDuration());
        mPbPlayBar.setProgressValue((int) BaseAppHelper.get().getMusicService().getCurrentPosition());
    }

    /**
     * 展示页面
     */
    private void showPlayingFragment() {
        if (isPlayFragmentShow) {
            return;
        }
        FractionManager fractionManager = null;
        if (getFractionManager().isPresent()) {
            fractionManager = getFractionManager().get();
            FractionScheduler ft = fractionManager.startFractionScheduler();
            if (mPlayFragment == null) {
                mPlayFragment = PlayMusicFragment.newInstance("OnLine");
                mPlayFragment.setSlice(this);
                ft.replace(ResourceTable.Id_content, mPlayFragment);
            } else {
                mPlayFragment.initData();
                ft.show(mPlayFragment);
            }
            ft.submit();
            isPlayFragmentShow = true;
        }
    }

    /**
     * 获取FractionManager
     *
     * @return fractionManager对象
     */
    private Optional<FractionManager> getFractionManager() {
        Ability ability = getAbility();
        if (ability instanceof FractionAbility) {
            FractionAbility fractionAbility = (FractionAbility) ability;
            return Optional.ofNullable(fractionAbility.getFractionManager());
        }
        return Optional.empty();
    }

    /**
     * 隐藏页面
     */
    private void hidePlayingFragment() {
        FractionManager fractionManager = null;
        if (getFractionManager().isPresent()) {
            fractionManager = getFractionManager().get();
            FractionScheduler ft = fractionManager.startFractionScheduler();
            ft.hide(mPlayFragment);
            ft.submit();
            isPlayFragmentShow = false;
        }
    }
}
